/**
 *@Title: SelectorClientTest.java
 *@Description: TODO
 *@author:Lau
 *@date 2017年7月9日 下午7:40:44 
 *@version V1.0
 */
package com.lty.nio.selectortest;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;


/** 
* @ClassName: SelectorClientTest 
* @Description: NIO选择器实例服务端
* @author Lau 
* @date 2017年7月9日 下午7:40:44 
*  
*/
public class SelectorServerTest {
	private Selector selector;
	private int keys = 0;
	private ServerSocketChannel serverChannel = null;
	
	/***
	 * 
	* @Title: initServer 
	* @Description: 初始化服务端的连接通道和选择器，注册事件
	* @throws Exception
	* void
	* @throws
	 */
	private void initServer() throws Exception{
		//打开一个Selector选择器
		this.selector = Selector.open();
		
		//打开一个SockChannel通道，但未进行连接
		serverChannel = ServerSocketChannel.open();

		serverChannel.socket().bind(new InetSocketAddress(8888));
		
		//设置非阻塞
		serverChannel.configureBlocking(false);
		
		//向selector注册accept事件
		serverChannel.register(this.selector, SelectionKey.OP_ACCEPT);
	}
	
	/***
	 * 
	* @Title: read 
	* @Description: 启动服务
	* @throws Exception
	* void
	* @throws
	 */
	public void read(SelectionKey key)throws Exception{
		SocketChannel channel = (SocketChannel) key.channel();
		ByteBuffer buff = ByteBuffer.allocate(1024);
		int len = channel.read(buff);
		String msg = "服务端接收到的消息：" + new String(buff.array(), 0, len);
		System.out.println(msg);
	}
	
	/***
	 * 
	* @Title: listen 
	* @Description: 监听选择器事件
	* @throws Exception
	* void
	* @throws
	 */
	public void listen() throws Exception{
		System.out.println("服务器已经成功启动...");
		//轮询
		while(true){
			//让选择器至少有一个通道就绪事件
			keys = this.selector.select();
			
			if(keys > 0){
				Iterator<SelectionKey> iterator = this.selector.selectedKeys().iterator();
				while(iterator.hasNext()){
					SelectionKey key = iterator.next();
					iterator.remove();
					
					//客户端请求连接事件
					if(key.isAcceptable()){
						serverChannel = (ServerSocketChannel) key.channel();
					
						//获取客户端连接通道
						SocketChannel channel = serverChannel.accept();
						channel.configureBlocking(false);
						
						//给客户端发送消息
						channel.write(ByteBuffer.wrap("Hello,Client!".getBytes()));
						
						//向选择器注册读事件
						channel.register(this.selector, SelectionKey.OP_READ);
					}
					else if(key.isReadable()){
						read(key);
					}
				}
			}
			else{
				//System.out.println("server select finished without any keys!");
			}
		}
	}
	
	/***
	 * 
	* @Title: start 
	* @Description: 启动服务
	* @throws Exception
	* void
	* @throws
	 */
	public void start()throws Exception{
		initServer();
		listen();
	}
	
	public static void main(String[] args) throws Exception {
		new SelectorServerTest().start();
	}
}
